<?php
declare(strict_types=1);
// 部门档案
namespace app\admin_v1\controller;

use think\facade\Db; //门面模式
use app\admin_v1\model\GroupBranchDepartments as MYSQL; //导入模型

class GroupBranchDepartments
{
    // 新增
    public function New()
    {
        $query = request()->param();
        $sqldb = MYSQL::create(
            [
                "dbid" => common__guid()["salt_any"], //数据编号.唯一
                "name" => (isset($query["name"]) && !empty($query["name"])) ? $query["name"] : "未设置名称", //名称
                "state" => $query["state"] ?? "A", //状态
                "memo" => !empty($query["memo"]) ? $query["memo"] : null, //备注
                "time_new" => time(), //创建时间
                "time_up" => time(), //修改时间


                "group_dbid" => $query["group_dbid"] ?? "1001", //集团数据编号
                "branch_dbid" => $query["branch_dbid"] ?? "1001", //机构数据编号
                "vid" => $query["vid"] ?? (string) mt_rand(1000, 9999), //部门自编号_可由上级随意更改
                "ap" => $query["ap"] ?? "P", //标记_P普通部门K虚拟部门

            ],
            // 许可写入的字段
            [
                "dbid", //数据编号.唯一
                "name", //名称
                "state", //状态
                "memo", //备注
                "time_new", //创建时间
                "time_up", //修改时间

                "group_dbid", //集团数据编号
                "branch_dbid", //机构数据编号
                "vid", //部门自编号_可由上级随意更改
                "ap", //标记_P普通部门K虚拟部门
            ]
        );
        $apidb = [
            "code" => 200,
            "msg" => "部门档案-新增成功",
            "query" => $query,
            "data_now" => $sqldb->toArray(),
            "data" => ["id" => $sqldb->id],
        ];
        return (json($apidb));
    }
    // 修改
    public function Up()
    {
        $query = request()->param();
        $sqldb = MYSQL::where([
            ["id", "=", $query["id"]],
            ["dbid", "=", $query["dbid"]],
        ])->find();
        $db_old = [];//修改前的数据
        if ($sqldb != null) {
            $db_old = $sqldb->toArray();

            $sqldb->name = $query["name"]; //名称
            $sqldb->state = $query["state"]; //状态
            $sqldb->memo = $query["memo"]; //备注
            $sqldb->time_up = time(); //修改时间

            $sqldb->group_dbid = $query["group_dbid"]; //集团数据编号
            $sqldb->branch_dbid = $query["branch_dbid"]; //机构数据编号
            $sqldb->vid = $query["vid"]; //部门自编号_可由上级随意更改
            $sqldb->ap = $query["ap"]; //标记_P普通部门K虚拟部门

            $umsg = $sqldb->save();
            if ($umsg !== false) {
                $msg = "更新成功";
                $code = 200;
            } else {
                $msg = "更新失败";
                $code = 201;
            }
        } else {
            $msg = "数据不存在";
            $code = 201;
        }
        $apidb = [
            "code" => $code,
            "msg" => $msg,
            "db_old" => $db_old,//修改前的数据
            "db_now" => $sqldb,
            "query" => $query,
            "cache" => cache("userdb_" . request()->header("token")),
            "help" => ["api_name" => "部门档案-修改", "db_old" => "修改前的数据", "db_now" => "修改后的数据"], //API信息
        ];
        return (json($apidb));
    }
    // 列表
    public function List()
    {
        $query = request()->param();
        // 请求方式验证
        if (!request()->isPost()) {
            $apidb = ["code" => 201, "msg" => "请求有误-不是Post方式!",];
            return json($apidb);
        }
        $limit = request()->param("limit", 10, "trim"); //每页行数
        $current = request()->param("current", 1, "trim"); //页码
        $SearchField = request()->param("SearchField", "id", "trim"); //搜索字段
        $SearchOperator = request()->param("SearchOperator", "LIKE", "trim"); //搜索查询表达式
        $SearchaAtistop = strval(request()->param("SearchaAtistop", "", "trim")); //搜索关键词
        $SearchaSort = request()->param("SearchaSort", "DESC", "trim"); //搜索排序方式ASE,DESC升降序
        $SearchaSortField = request()->param("SearchaSortField", "id", "trim"); //排序字段
        $query = request()->param();
        // strval();//转成字符串
        // echo gettype(); //打印变量的类型
        // 查询表达式
        if ($SearchOperator == "LIKE") {
            $SearchaAtistop = "%" . $SearchaAtistop . "%";
        }
        if ($SearchField == "time_new" || $SearchField == "time_up") {
            if ($SearchOperator == ">" || $SearchOperator == "<") {
                $SearchaAtistop = strtotime(strval($SearchaAtistop));
                if ($SearchField == "time_new") {
                    $SearchField = "time_new";
                } else if ($SearchField == "time_up") {
                    $SearchField = "time_up";
                }
            }
        }
        $help = [
            "db" => [
                "total" => "数据总行数",
                "per_page" => "每页数量",
                "current_page" => "当前页码",
                "last_page" => "最后一页/总页数",
                "data" => "数据集"
            ]
        ];
        $sqldb = MYSQL::where([
            [$SearchField, $SearchOperator, $SearchaAtistop],
        ])
            ->order($SearchaSortField, $SearchaSort)
            ->paginate([ //[文档]https://www.kancloud.cn/manual/thinkphp6_0/1037638
                "list_rows" => $limit, // 每页数量
                "page" => $current, // 当前页
            ]);
        //设置允许字段
        $sqldb = $sqldb->visible([
        ]);
        //设置隐藏字段
        $sqldb = $sqldb->hidden([
            // "id", //主键
        ]);
        //设置追加字段
        $sqldb = $sqldb->append([
            "state2", //状态A正常B停用
            "time_new2", //创建时间
            "time_up2", //修改时间

            "ap2", //标记_P普通部门K虚拟部门
            "group_dbid2", //集团数据编号
            "branch_dbid2", //机构数据编号
        ]);

        // 设置数据字段获取器
        // 状态A正常B停用
        $sqldb = $sqldb->withAttr("state2", function ($value, $data) {
            $res = ["A" => "正常", "B" => "停用", "" => "", null => ""];
            return $res[$data["state"]] ?? "---";
        });

        // 标记_P普通部门K虚拟部门
        $sqldb = $sqldb->withAttr("ap2", function ($value, $data) {
            $res = ["P" => "普通部门", "K" => "虚拟部门", "" => "", null => ""];
            return $res[$data["ap"]] ?? "---";
        });

        // 集团数据编号
        $sqldb = $sqldb->withAttr("group_dbid2", function ($value, $data) {
            // 返回某个字段的值
            $name = Db::table('admin__i_group')->where('dbid', $data["group_dbid"])->value('name');
            return $name ?? "---";
        });
        // 机构数据编号
        $sqldb = $sqldb->withAttr("branch_dbid2", function ($value, $data) {
            // 返回某个字段的值
            $name = Db::table('admin__i_group_branch')->where('dbid', $data["branch_dbid"])->value('name');
            return $name ?? "---";
        });

        $sqldb = $sqldb->withAttr("time_new2", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_new"]);
        });
        $sqldb = $sqldb->withAttr("time_up2", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_up"]);
        });


        $sqldb2 = $sqldb->toArray();
        //  当前页起始行
        if ($current > 1) {
            $index2 = $limit * $current - $limit + 1;
        } else {
            $index2 = 1;
        }
        // echo "当前总下标：" . $index2;
        for ($x = 0; $x < count($sqldb); $x++) {
            // $li_db[$x]["apitxtx"] = json_decode($li_db[$x]["apitxt"], true); //格式化插入
            // unset($li_db[$x]); //删除数组中的元素
            // ksort($li_db[$x]);//根据关联数组的键，对数组进行升序排列
            $sqldb2["data"][$x]["index1"] = $x + 1;
            $sqldb2["data"][$x]["index2"] = $index2;
            $index2++;
            // dump($sqldb2);
            // $sqldb[$x]["idb"] = $x++;
        }

        $apidb = [
            "code" => 200,
            "msg" => "部门档案-列表",
            "db" => $sqldb2,
            "_cache" => cache("userdb_" . request()->header("token")),
            "query" => $query,
            "sql" => MYSQL::getLastSql(), //输出上次执行的sql语句/也可以使用fetchSql方法直接返回当前的查询SQL而不执行，例如：echo User::fetchSql()->find(1);
            "api" => ["code" => "001", "name" => "部门档案-列表", "help" => $help], //API信息

        ];
        return (json($apidb));
    }
}
